import type vueHook from 'alova/vue'
import type { ApiResponse } from './type'
import type { LoginResult } from '@/apis/auth'
import { createServerTokenAuthentication } from 'alova/client'
import router from '@/router'
import { useAuthStore } from '@/stores/modules/auth'
import { Code } from './type'

const { onAuthRequired, onResponseRefreshToken } = createServerTokenAuthentication<typeof vueHook>({
  // 登录接口的回调方法
  // 当接口中的meta.authRole = login时 接口请求成功回调此函数
  login: async (response) => {
    const res = await response.clone().json() as ApiResponse<LoginResult>
    const authStore = useAuthStore()
    // 请求成功设置token
    if (res.code === Code.SUCCESS) {
      authStore.token = res.data.token
    }
  },
  // 退出接口的回调
  // 当接口中的meta.authRole = logout时 退出接口请求成功回调此函数
  logout: async () => {
    const authStore = useAuthStore()
    authStore.token = ''
  },
  // 在每个请求上附加token
  assignToken: (method) => {
    const authStore = useAuthStore()
    method.config.headers.Authorization = authStore.token
  },
  // 刷新token逻辑
  refreshTokenOnSuccess: {
    // 判断是否过期 当接口是401或者返回的code是NOT_LOGIN就表示过期
    isExpired: async (res) => {
      if (res.status === 401) {
        return true
      }
      if (res.status !== 200) {
        throw new Error(res.statusText)
      }
      const data = await res.clone().json() as ApiResponse
      return data.code === Code.NOT_LOGIN
    },
    // 处理过期 这里可以请求刷新token 也可以弹窗提示用户登录已过期
    handler: async () => {
      // 跳转到登录页
      router.push({ name: 'login' })
      throw new Error('token expired')
    },
  },
})

export {
  onAuthRequired,
  onResponseRefreshToken,
}
